<template>
	<div class="system-add-role-container">
		<el-dialog :title="state.title" v-model="state.isShowDialog" width="600px">
			<easy-form :fieldList="fieldList.formItem" :model="modelData" ref="formRef" :options="options" ></easy-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { reactive, toRefs,ref} from 'vue'
	import { usersApi } from '/@/api/system/users'
	import { error, success } from '/@/utils/msg'
	import EasyForm from '/@/components/form/index.vue'

	interface stateUsers {
		isShowDialog: boolean,
		title:string
	}
  

  const formRef = ref()

  // form 表单
	const modelData = ref<Record<string, any>>({
		id : "0",
		username : '',
		nickname : '',
		//password : '',
    roles : [],
    remark : '',
    phone : '',
    email : ''
	})

  // 保存
	const usersSave = async()=> {
		return await usersApi().save( modelData.value )
	}

  // 详情
  const detail = async()=>{
    return await usersApi().detail(modelData.value)
  }


	// 
	const state = reactive<stateUsers>({
		isShowDialog: false,
		title : '新增'
	});

  // 配置
  const fieldList = reactive({formItem:[]})

  // Options 配置项
	const options = reactive<Form.Options>({
		showResetButton:false
	})

  // 打开弹窗
	const openDialog = async( row? : Record<string, any> , title?:string) => {
		state.title = title??'新增'
    modelData.value = row 
    const {code,data,form_item} = await detail()
    if ( Object.keys(data).length > 0) {
      modelData.value = data as Record<string, any>
      console.log(modelData.value)
    }
    fieldList.formItem = form_item as Form.FieldItem[]
    
    if ( code == 0 || code == true ) state.isShowDialog = true
	}

	// 关闭弹窗
	const closeDialog = () => {
		state.isShowDialog = false;
	};

	// 取消
	const onCancel = () => {
		closeDialog()
	};


	const emit = defineEmits<{
		(e:"on-load"):void
	}>()
	
  // 新增
	const onSubmit = async() => {
		if (!formRef) return
		formRef.value.validData().then( async(valid) => {
			if ( valid ) {
				let {code,msg} = await usersSave()
				if ( code === 0 || code === true ) {
					success(msg)
					onCancel()
					emit('on-load')
				} else {
					error(msg)
				}
			}
    })
	}

  defineExpose({
    ...toRefs(state),
    openDialog
  })
</script>